import os
from ..core import Builder, Namespace, CustomParams
from ..common import common_namespace


class GabotProjectBuilder(Builder):
    PARAMS_PREFIX = "proj_"
    
    @classmethod
    def scan(cls, node):
        node.namespace = common_namespace.copy()
        node.params = Namespace(node.params)
        node.namespace["params"] = node.params
        execfile(node.relname, node.namespace)
        node.tool_inputs = set()
        if "inputs" in node.namespace:
            for fn in node.namespace["inputs"]:
                child = cls._process_input(node, fn)
                node.tool_inputs.add(child)
        if "misc" in node.namespace:
            for fn in node.namespace["misc"]:
                cls._process_input(node, fn)
    
    @classmethod
    def _process_input(cls, node, fn):
        if fn is None:
            return
        if isinstance(fn, CustomParams):
            child = node.create_child(fn.filename)
            child.params = Namespace(node.params)
            for k, v in fn.params.iteritems():
                child.params[k] = v
        else:
            child = node.create_child(fn)
            child.params = node.params
        return child
    
    @classmethod
    def get_output_name(cls, node):
        return node.namespace.get("output")
    
    @classmethod
    def build(cls, node):
        if node.output:
            infiles = [n.output for n in node.tool_inputs if n.output]
            if "tool" not in node.namespace:
                raise ProjectError("%s: 'tool' is required when 'output' "
                    "is given" % (node,))
            node.namespace["tool"](infiles, node.output, node.params)


def register_builder():
    GabotProjectBuilder.register("gabot")



